"""
浏览一个需要登录才能看的url
"""
import requests

# 浏览一个需要登录才能看的url，查看Gitee上我的所有项目
url = "https://gitee.com/pyt5/projects"

# 1)使用session完成登录（发送post请求），session会实现状态保持
url_login = 'https://gitee.com/login'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'
}
# post请求有请求体数据,网页上拷贝过来后构造成字典
data = {
    'encrypt_key': 'password',
    'utf8': '✓',
    'authenticity_token': '+cLWAmD1TN2JNlQfJmVFlWmvdEsiYfXCsYN5KIR1BL0=',
    'redirect_to_url': '',
    'user[login]': 'zjitc_pyt@sina.com',
    'encrypt_data[user[password]]': 'IJ2U8FwSYRZl2WdjkOHWSnodjonTWWK9wSF1GIoG4IwfnFCZGpijkJhmgArihCiHaTPTLdpB+0rBl0xPyNfvVALWmjWnfiYUlQ2T1tEvTsWYpDq9i+D5IElOG48TtmmcFmXabSeTXKfMcFHmb/oWCdgD/TbdIDwKWXhbQCCYoLg=',
    'user[remember_me]': '0'
}
# 使用session代替requests发送post请求
session = requests.session()
r1 = session.post(url_login, headers=headers, data=data)
print(r1.status_code)
print(r1.content.decode())

# 2）使用session查看需要登录后才能看的url，不需要带cookie，session会自动实现
url = 'https://gitee.com/pyt5/projects'
r2 = session.get(url, headers=headers)
with open('session.html', 'w', encoding='utf-8') as f:
    f.write(r2.content.decode())
